package com.lsf.modules.system.handle;

import com.lsf.config.StaticConfig;
import com.lsf.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author Alexander
 */
@Slf4j
public class EmailSendMsgHandle {

    private static String emailFrom;

    private static String title;

    private static String content;

    public static void setEmailFrom(String emailFrom) {
        EmailSendMsgHandle.emailFrom = emailFrom;
    }

    public static void setTitle(String title) {
        EmailSendMsgHandle.title = title;
    }

    public static void setContent(String content) {
        EmailSendMsgHandle.content = content;
    }

    public static void SendMsg(String receiver, String captcha) {
        JavaMailSender mailSender = (JavaMailSender) SpringContextUtils.getBean("mailSender");
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class);
        if (StringUtils.isEmpty(emailFrom)) {
            setEmailFrom(staticConfig.getEmailFrom());
        }
        if (StringUtils.isEmpty(title)) {
            setTitle(staticConfig.getTitle());
        }
        if (StringUtils.isEmpty(content)) {
            String msg = staticConfig.getContent();
            msg = msg.replace("{code}", captcha);
            setContent(msg);
        }
        try {
            helper = new MimeMessageHelper(message, true);
            //设置发送方邮箱地址
            helper.setFrom(emailFrom);
            helper.setTo(receiver);
            helper.setSubject(title);
            helper.setText(content, true);
            mailSender.send(message);
        } catch (
                MessagingException e) {
            log.error(e.getMessage(), e);
        }

    }
}
